


# coding='utf-8'
"""t-SNE对手写数字进行可视化"""
from time import time
import numpy as np
import matplotlib.pyplot as plt

from sklearn import datasets
from sklearn.manifold import TSNE

import pandas as pd


def get_data():
    digits = datasets.load_digits(n_class=6)
    data = digits.data
    label = digits.target
    n_samples, n_features = data.shape
    return data, label, n_samples, n_features

def map_labels_to_numbers(labels):
    unique_labels = np.unique(labels)
    label_map = {label: i for i, label in enumerate(unique_labels)}
    mapped_labels = np.array([label_map[label] for label in labels])
    return mapped_labels, label_map


def get_data_from_csv(csv_file):
    # 从CSV文件中读取数据
    df = pd.read_csv(csv_file)
    
    # 获取样本数据和标签
    data = df.iloc[:, 1:].values  # 获取除第一列外的所有列作为特征数据
    # label = df.iloc[:, 0].values  # 获取第一列作为标签数据
    label_str = df.iloc[:, 0].values  # 获取第一列作为字符串标签数据
    
    # 将类别标签映射为数字
    label, label_map = map_labels_to_numbers(label_str)
    
    # 获取样本数和特征数
    n_samples, n_features = data.shape
    
    return data, label, n_samples, n_features

def plot_embedding(data, label, title):
    x_min, x_max = np.min(data, 0), np.max(data, 0)
    data = (data - x_min) / (x_max - x_min)

    fig = plt.figure()
    # fig = plt.figure(figsize=(10, 8))
    
    ax = plt.subplot(111)
    # 定义颜色映射，每个类别对应一个颜色
    colors = ['r', 'b', 'g', 'c', 'm', 'y']  # 可以根据需要添加更多的颜色
    
    for i in range(data.shape[0]):
        color_index = label[i] % len(colors)
        plt.text(data[i, 0], data[i, 1], str(label[i]),
                 color=colors[color_index],
                 fontdict={'weight': 'bold', 'size': 9})
    plt.xticks([])
    plt.yticks([])
    plt.title(title)
    return fig


def main():
    # data, label, n_samples, n_features = get_data()
    # csv调用
    data, label, n_samples, n_features = get_data_from_csv("totalFeaturesForRight_Lee20240111.csv")
    print('data.shape',data.shape) 
    print('label',label)
    print('label中数字有',len(set(label)),'个不同的数字')
    print('data有',n_samples,'个样本')
    print('每个样本',n_features,'维数据')
    print('Computing t-SNE embedding')
    
    # tsne = TSNE(n_components=2, init='pca', random_state=0)
    tsne = TSNE(n_components=2, random_state=0)
    t0 = time()
    result = tsne.fit_transform(data)
    print('result.shape',result.shape)
    fig = plot_embedding(result, label,
                         't-SNE embedding of the digits (time %.2fs)'
                         % (time() - t0))
    
    # # 扩大x轴范围与y轴范围
    # plt.xlim((np.min(result[:, 0]) - 10, np.max(result[:, 0]) + 10))
    # plt.ylim((np.min(result[:, 1]) - 10, np.max(result[:, 1]) + 10))
    
    
    # plt.show(fig)
    plt.show()

if __name__ == '__main__':
    main()



